<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column label="头像" width="80" align="center">
        <template slot-scope="scope">
          <el-avatar :size="30" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="100" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="nickname" label="昵称" width="100" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="phone" label="手机号码" width="150" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="email" label="电子邮箱" width="200" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="简介" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="是否启用" width="100" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.enable"
              active-color="#13ce66"
              inactive-color="#ccc"
              :active-value="1"
              :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="配置角色" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="small" @click="openEditRoleDialog(scope.row)">配置角色</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-search" circle type="primary"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button size="small" icon="el-icon-delete" circle type="danger"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px auto;text-align: right;">
      <el-pagination
          @current-change="changePageNum"
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage">
      </el-pagination>
    </div>

    <el-dialog title="配置角色" :visible.sync="dialogRoleFormVisible"
               @closed="resetForm('editRoleForm')">
      <el-form :model="editRoleForm" :rules="rules" ref="editRoleForm">
        <el-form-item>
        <p style="text-align: center; margin: 10px 10px;font-weight: bold; font-size: 22px">
          {{editRoleForm.nickname}}
        </p>
        <div style="text-align: center;">
          <el-transfer
              style="text-align: left; display: inline-block"
              v-model="editRoleForm.roleIds"
              :props="{key: 'id',label: 'name'}"
              :data="roleListOptions"
              @change="submitEditRoleForm"
              filterable
              :render-content="renderFunc"
              :titles="['角色列表', '已有角色']"
              :button-texts="['删除角色', '添加角色']"
              :format="{noChecked: '${total}',hasChecked: '${checked}/${total}'}">
           </el-transfer>
        </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleFormVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="用户信息" :visible.sync="dialogFormVisible"
               @closed="resetForm('editForm')">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="130px">
        <el-form-item label="用户名">
          <el-input v-model="showUsername" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="editForm.phone" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description" autocomplete="off" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import global from '../../../Global'
let preAdminUrl = global.preAdmins ;
let preRoleUrl = global.preRoles ;
let queryAll = global.queryAll ;
export default {
  data() {
    return {
      tableData: [],
      total: 0,
      pageSize: 0,
      currentPage: 1,
      showUsername: '',
      dialogFormVisible: false,
      editForm: {
        id: '',
        nickname: '',
        phone: '',
        email: '',
        description: ''
      },
      dialogRoleFormVisible: false,
      roleListOptions: [],
      editRoleForm: {
        adminId: '',
        nickname: '',
        roleIds: []
      }

    }
  },
  methods: {
    //角色列表数据展示
    renderFunc(h, option) {
      return <span>{ option.id } - { option.name }</span>;
    },
    // 切换启用状态
    toggleEnable(admin){
      let enableText = ['禁用', '启用'];
      let urlMethod = ['disable','enable'];
      let enable = admin.enable;
      let url = preAdminUrl + "/" + admin.id + "/" + urlMethod[enable];

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify.success({title: '成功',
            message: '将【' + admin.nickname + '】的启用状态修改为【' + enableText[enable] + '】成功！'
          });
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //角色修改Dialog
    openEditRoleDialog(admin){
      this.editRoleForm.adminId = admin.id;
      this.editRoleForm.nickname = admin.nickname;
      this.dialogRoleFormVisible = true;
      this.loadAllRoleList();
      this.loadAdminRoleList();
    },
    //角色修改提交
    submitEditRoleForm(value, direction, movedKeys) {
      let urlMethod = '';
      if(direction == 'left'){
        urlMethod = 'deletesAdminRole';
      }else if(direction == 'right'){
        urlMethod = 'insertsAdminRole';
      }
      let url = preAdminUrl + "/" + this.editRoleForm.adminId + "/" + urlMethod
                +"?roleIds="+movedKeys;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify.success({title: '成功',
            message: '配置角色成功！'
          });
          this.loadAdminList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });

      console.log(value, direction, movedKeys);
    },
    //管理员修改Dialog
    openEditDialog(admin){
      let url = preAdminUrl + "/" + admin.id;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.showUsername = admin.username;
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        }
      });
    },
    //管理员删除确认提示
    openDeleteConfirm(admin) {
      this.$confirm('此操作将永久删除【 ' + admin.id + '-' + admin.username + ' 】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(admin);
      }).catch(() => {
      });
    },
    //管理员删除
    handleDelete(admin){
      let url = preAdminUrl + "/" + admin.id + "/delete";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify.success({title: '成功',
            message: '删除成功'
          });

          this.loadAdminList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        }else if(jsonResult.state == 40900){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });

    },
    //分页——翻页
    changePageNum(value){
      this.$router.replace("?pageNum="+value);
      this.loadAdminList();
    },
    //加载管理员列表
    loadAdminList(){
      let pageNum = this.$router.currentRoute.query.pageNum;
      if(!pageNum){
        pageNum = 1;
      }
      let url = preAdminUrl+"/users?pageNum="+ pageNum;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        }else if(jsonResult.state == 40100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              localStorage.removeItem("localJwt");
              this.$router.push("/login");
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //加载角色全列表
    loadAllRoleList(){
      let url = preRoleUrl+queryAll;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.roleListOptions = jsonResult.data.list;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //获取角色所有的全部角色
    loadAdminRoleList(){
      let url = preAdminUrl + "/" +this.editRoleForm.adminId + "/roles";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.editRoleForm.roleIds = jsonResult.data;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    resetForm(formName) {
      this.roleListOptions = [];
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadAdminList();
  }
}
</script>
<style>
.el-transfer-panel{
  width:260px !important;
}
</style>